<template>
  <div class="row inner-form" style="padding-top: 15px;background: #fff" v-loading="loading">
    <div class="col">
      <div class="detail-content">
        <span class="title">采购单详情</span>
        <div class="dashed-line"></div>
      </div>
      <div>
        <h-purchase-info-display v-model="purchase" sn/>
      </div>

      <div class="row">
        <div class="col" style="background: #f0f2f5;padding: 15px">
          <div class="detail-content" style="padding: 15px;">
            <span class="title">{{title}}</span>
          </div>
          <div class="form-content-detail">
            <el-form :model="form" :rules="rules" ref="form" class="custom-form">
              <el-form-item label="商品货号:" prop="itemNo">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <h-item-no-choose v-model="form.itemNo" @change="itemChange"></h-item-no-choose>
                  </el-col>
                  <el-col :span="11">
                    <span>输入商品对应的具体货号</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品名称:" prop="goodName">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <h-good-choose v-model="form.goodName" :id.sync="form.goodId" @change="goodChange"></h-good-choose>
                  </el-col>
                  <el-col :span="11">
                    <span>请选择已有的商品名称，如没有则直接输入</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品品牌:" prop="brandId">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <h-brand-choose v-model="form.brandId"></h-brand-choose>
                  </el-col>
                  <el-col :span="11">
                    <span>请选择商品的品牌名称或直接输入新的品牌</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品分类:" prop="categoryIds">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <h-good-category-choose v-model="form.categoryIds"></h-good-category-choose>
                  </el-col>
                  <el-col :span="11">
                    <span>请选择商品的分类信息</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="货币类型:" prop="currencyId">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <h-currency-choose v-model="form.currencyId"></h-currency-choose>
                  </el-col>
                  <el-col :span="11">
                    <span>请选择商品采购时的货币类型</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <h-spec-input v-model="form.specs"></h-spec-input>

              <el-form-item label="采购价格:" prop="purchasePrice">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number v-model="form.purchasePrice" :min="0"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入采购时的商品原价</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="售出汇率:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.0001" v-model="form.exchangeRate"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入商品售出的汇率信息</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="结算汇率:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.0001" v-model="form.closeExchangeRate"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入结算时候的汇率信息</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="采购数量:" prop="num">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="1" v-model="form.num"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入采购的件数</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="外币运费:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.01" v-model="form.globalFreight"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入外币结算的运费</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="运费:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.01" v-model="form.freight"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span>请输入人民币结算的运费</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="成本单价:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.01" v-model="unitPrice"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span class="red">成本单价(采购单价)=采购价格*结算汇率+外币运费*结算汇率+运费。</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品折扣:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="1" v-model="form.discount" :min="0" :max="100"></el-input-number>
                    %
                  </el-col>
                  <el-col :span="11">
                    <span class="red">输入采购商品时的商品折扣比例</span>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-form-item label="商品售价:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.01" v-model="price"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span class="red">商品售价(售卖价格)=采购价格*销出汇率*(1-商品折扣)+外币运费*销出汇率+运费。</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="结算总额:" prop="cost">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input-number :step="0.0001" v-model="allPrice"></el-input-number>
                  </el-col>
                  <el-col :span="11">
                    <span class="red"> 结算总额=采购数量*(采购价格*结算汇率*(1-商品折扣)+外币运费*结算汇率+运费)。</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="淘宝链接:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input v-model="form.tbUrl" placeholder="淘宝链接"></el-input>
                  </el-col>
                  <el-col :span="11">
                    <span> 商品对应的淘宝链接,需要淘宝付款时填写 </span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="是否会员优惠:">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-radio v-model="form.special" :label="1">优惠</el-radio>
                    <el-radio v-model="form.special" :label="0">不优惠</el-radio>
                  </el-col>
                  <el-col :span="11">
                    <span>该商品是否针对会员优惠</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="商品图片:" prop="imgs">
                <el-row :gutter="0" style="padding-left: 15px;">
                  <h-pic-upload-and-choose :files="form.imgs" owner="admin"></h-pic-upload-and-choose>
                </el-row>
              </el-form-item>
            </el-form>
            <div class="col">
              <el-button type="primary" v-if="type==1" @click="create(false)"><i class="fa fa-plus"></i> 添加详情
              </el-button>
              <el-button type="primary" v-else @click="create(false)"><i class="fa fa-save"></i> 保存详情</el-button>
              <el-button type="success" @click="goback"><i class="fa fa-sign-out"></i> 返回</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import AdminService from 'src/service/admin'
  import HPicUploadAndChoose from 'src/components/common/HPicUploadAndChoose'
  import HBrandChoose from 'src/components/common/choose/HBrandChoose'
  import HItemNoChoose from 'src/components/common/HItemNoChoose'
  import HGoodCategoryChoose from 'src/components/common/choose/HGoodCategoryChoose'
  import HCurrencyChoose from 'src/components/common/select/HCurrencySelect'
  import HGoodChoose from 'src/components/common/choose/HGoodChoose'
  import HSpecInput from 'src/components/common/HSpecInput'
  import HPurchaseInfoDisplay from 'src/components/admin/purchase/components/PurchaseInfoDisplay'

  export default {
    name: 'HPurchaseDetailEdit',
    components: {
      HPicUploadAndChoose, HBrandChoose, HItemNoChoose, HGoodCategoryChoose, HPurchaseInfoDisplay,
      HCurrencyChoose, HGoodChoose, HSpecInput
    },
    data() {
      return {
        title: null,
        form: {
          id: null,
          itemNo: null,
          purchasePrice: 0.0,
          sellPrice: 0.0,
          freight: 0.0,
          currencyId: 6,
          num: 1,
          discount: 0,
          closeExchangeRate: 0.0,
          exchangeRate: 0.0,
          categoryId: null,
          categoryIds: null,
          categoryIdPath: null,
          goodId: null,
          goodName: '',
          brandId: null,
          purchaseId: 0,
          unitPrice: 0,
          cost: 0.00,
          globalFreight: 0.0,
          tbUrl: '',
          special: 0,
          imgs: [],
          specs: {
            ids: null,
            datas: []
          }
        },
        loading: false,
        type: 1,
        purchase: {},
        rules: {
          goodName: [
            {required: true, message: '请输入品牌名称', trigger: 'change'}
          ],
          categoryIds: [
            {required: true, message: '请选择商品分类', trigger: 'change'}
          ],
          itemNo: [
            {required: true, message: '请输入商品的具体货号', trigger: 'change'}
          ],
          brandId: [
            {required: true, message: '请选择商品品牌', trigger: 'change'}
          ],
          currencyId: [
            {required: true, message: '请选择货币类型', trigger: 'change'}
          ],
          imgs: [
            {required: true, message: '请上传至少一张图片', trigger: 'change'}
          ]
        }
      }
    },
    computed: {
      price: {
        get: function () {
          this.form.sellPrice = parseFloat((this.form.purchasePrice * this.form.exchangeRate * (100 - this.form.discount) / 100 +
            this.form.globalFreight * this.form.exchangeRate + this.form.freight).toFixed(2))
          return this.form.sellPrice
        },
        set: function (v) {
          this.form.sellPrice = v
        }

      },
      unitPrice: {
        get: function () {
          this.form.unitPrice = parseFloat((this.form.purchasePrice * this.form.closeExchangeRate +
            this.form.globalFreight * this.form.closeExchangeRate + this.form.freight).toFixed(2))
          return this.form.unitPrice
        },
        set: function (v) {
          this.form.unitPrice = v
        }
      },
      allPrice: {
        get: function () {
          this.form.cost = parseFloat((this.form.purchasePrice * this.form.num * this.form.closeExchangeRate * (100 - this.form.discount) / 100 +
            this.form.globalFreight * this.form.closeExchangeRate * this.form.num +
            this.form.freight * this.form.num).toFixed(2))
          return this.form.cost
        },
        set: function (v) {
          this.form.cost = v
        }
      }
    },
    methods: {
      itemChange: function (item) {
        this.form.goodId = item.good.id
        this.form.goodName = item.good.name
        this.form.brandId = item.brand.id
        this.form.exchangeRate = item.exchangeRate
        this.form.closeExchangeRate = item.closeExchangeRate
        this.form.currencyId = item.currency.id
        this.form.categoryIds = this.toArray(item.category.idPath)
        this.form.specs = item.specs
        this.form.tbUrl = item.tbUrl
        this.form.special = item.special
        this.form.purchasePrice = item.purchasePrice
        if (item.imgs != null) {
          this.form.imgs = item.imgs
        } else {
          this.form.imgs = []
        }
      },
      goodChange: function (item) {
        this.form.brandId = item.brand.id
        this.form.categoryIds = this.toArray(item.category.idPath)
        if (item.specs != null) {
          const ids = item.specs.map(data => {
            return data.id
          })
          this.form.specs = {
            'ids': ids.join(','),
            'datas': item.specs
          }

        }
        if (item.imgs != null) {
          this.form.imgs = item.imgs
        } else {
          this.form.imgs = []
        }

      },
      toArray: function (idpath) {
        if (idpath == null || idpath == undefined) {
          return []
        }
        const ids = idpath.split(',')
        const array = []
        for (let i = 0; i < ids.length; i++) {
          array.push(parseInt(ids[i]))
        }
        return array
      },
      create: function (go) {
        const me = this
        me.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.categoryIds != null && this.form.categoryIds.length > 0) {
              this.form.categoryId = this.form.categoryIds[this.form.categoryIds.length - 1]
              this.form.categoryIdPath = this.form.categoryIds.join(',')
            } else {
              this.form.categoryId = null
              this.form.categoryIdPath = null
            }
            AdminService.purchaseDetail(this.form).then(data => {
              if (data != null) {
                if (me.type == 1) {
                  me.$message.success('添加订单详情成功')
                } else {
                  me.$message.success('保存订单详情成功')
                }
                if (go) {

                } else {
                  me.goback()
                }
              }
            })
          } else {
            me.$message.error('请按要求填写信息!')
          }
        })
      },
      getPurchase: function (id, setForm) {
        const me = this
        AdminService.purchaseById(id).then(data => {
          if (data != null) {
            me.purchase = data.datas[0]
            if (setForm) {
              me.form.exchangeRate = me.purchase.exchangeRate;
              me.form.closeExchangeRate = me.purchase.closeExchangeRate;
              me.form.currencyId = me.purchase.currency.id;
            }
          }
        })
      },
      //获取详细信息
      getPurchaseDetail: function (id) {
        const me = this
        me.$nextTick(function () {
          me.loading = true;
          AdminService.purchaseDetailById(id).then(ds => {
            if (ds != null) {
              const data = ds.datas[0]
              me.getPurchase(data.purchaseId, false)
              me.form = {
                id: data.id,
                itemNo: data.itemNo,
                purchasePrice: data.purchasePrice,
                sellPrice: data.sellPrice,
                freight: data.freight,
                currencyId: data.currency.id,
                discount: data.discount,
                num: data.num,
                closeExchangeRate: data.closeExchangeRate,
                exchangeRate: data.exchangeRate,
                categoryId: data.category.id,
                categoryIds: this.toArray(data.category.idPath),
                categoryIdPath: data.category.idPath,
                goodId: data.good.id,
                goodName: data.good.name,
                brandId: data.brand.id,
                purchaseId: data.purchaseId,
                cost: data.cost,
                globalFreight: data.globalFreight,
                imgs: data.imgs,
                specs: data.specs,
                tbUrl: data.tbUrl,
                special: data.special
              }
            }
            me.loading = false;
          })
        });
      },
      goback: function () {
        this.$router.go(-1)
      }
    },
    mounted: function () {
      if (this.$route.meta.type == 'create') {
        this.form.purchaseId = this.$route.params.id
        this.getPurchase(this.form.purchaseId, true)
        this.title = '添加采购详情'
        this.type = 1
      } else {
        this.form.id = this.$route.params.id
        this.getPurchaseDetail(this.form.id)
        this.title = '编辑采购详情'
        this.type = 2
      }
    }
  }
</script>
